﻿using DoNet.Common.Helpers;
using DoNet.Common.Result;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace WechatMp.Web.Controllers.API
{
    [Route("[controller]")]
    [ApiController]
    public class JwtTokenController : ControllerBase
    {
        private readonly AppService appService;
        public JwtTokenController(AppService _appService)
        {
            appService = _appService;
        }

        /// <summary>
        /// 根据应用信息获得token令牌
        /// </summary>
        /// <param name="appid">应用唯一凭证，应用AppId</param>
        /// <param name="secret">应用密钥AppSecret</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Get(string appid, string secret)
        {
            CommonResult result = new CommonResult();
            var app = appService.GetAPP(appid, secret);
            if (app != null)
            {
                string strHost = Request.Headers["Origin"].ToString();
                if (app.RequestUrl.Contains(strHost))
                {
                    TokenProvider tokenProvider = new TokenProvider();
                    var tokenResult = tokenProvider.GenerateToken(appid, app.SecretVersion, secret);
                    if (tokenResult != null)
                    {
                        result.ResData = tokenResult;
                        result.ErrCode = "0";
                        result.Success = true;
                    }
                }
                else
                {
                    result.ErrCode = "40002";
                    result.ErrMsg = "调用接口的服务器URL地址未授权！你当前请求主机：" + strHost + "";
                }
            }
            else
            {
                result.ErrCode = "40001";
                result.ErrMsg = "获取access_token时AppId或AppSecret错误！";
            }
            return Content(JsonHelper.SerializeObject(result));
        }

        /// <summary>
        /// 验证token的合法性。
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet("CheckToken")]
        [AllowAnonymous]
        public IActionResult CheckToken(string token)
        {
            CommonResult result = new CommonResult();
            TokenProvider tokenProvider = new TokenProvider();
            result = tokenProvider.ValidateToken(token);
            if (!result.Success)
            {
                if (result.ErrCode == "401")
                {
                    return Unauthorized(); // 返回401状态码
                }
            }
            return Content(JsonHelper.SerializeObject(result));
        }

        /// <summary>
        /// 刷新token。
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet("RefreshToken")]
        [AllowAnonymous]
        public IActionResult RefreshToken(string token)
        {
            CommonResult result = new CommonResult();
            if (!string.IsNullOrEmpty(token))
            {
                JwtSecurityToken jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(token);
                if (jwtToken != null)
                {
                    TokenProvider tokenProvider = new TokenProvider();
                    //根据应用获取token
                    if (jwtToken.Subject == GrantType.ClientCredentials)
                    {
                        TokenResult tresult = new TokenResult();
                        var claimlist = jwtToken?.Payload.Claims as List<Claim>;
                        if (claimlist != null)
                        {
                            var appId = claimlist[0].Value;
                            var app = appService.GetAPP(appId);
                            if (app != null)
                            {
                                string strHost = Request.Host.ToString();
                                if (app.RequestUrl.Contains(strHost))
                                {
                                    var tokenResult = tokenProvider.GenerateToken(appId, app.SecretVersion, app.AppSecret);
                                    if (tokenResult != null)
                                    {
                                        result.ResData = tokenResult;
                                        result.ErrCode = "0";
                                    }
                                }
                                else
                                {
                                    result.Success = true;
                                    result.ErrCode = "40002";
                                    result.ErrMsg = "调用接口的服务器URL地址未授权！你当前请求主机：" + strHost + "";
                                }
                            }
                            else
                            {
                                result.ErrCode = "40001";
                                result.ErrMsg = "获取access_token时AppId或AppSecret错误！";
                            }
                        }
                    }
                    // 用户账号密码登录获取token类型
                    else if (jwtToken.Subject == GrantType.Password)
                    {
                        var claimlist = jwtToken?.Payload.Claims as List<Claim>;
                        if (claimlist != null)
                        {
                            //CacheHelper cacheHelper = new CacheHelper();
                            //UserInfo userInfo = yuebonCacheHelper.Get<UserInfo>(CacheConst.KeyLoginUserInfo + claimlist[3].Value);
                            UserInfo userInfo = new UserInfo()
                            {
                                UserId = 1,
                                UserName = "超级管理员",
                                RealName = "超级管理员",
                                UserType = UserTypeEnum.SuperAdmin,
                                Role = [1, 2, 3]
                            };

                            var tokenResult = tokenProvider.LoginToken(userInfo, claimlist[0].Value);
                            TimeSpan expiresSliding = DateTime.Now.AddMinutes(120) - DateTime.Now;
                            //cacheHelper.Replace(CacheConst.KeyLoginUserInfo + claimlist[3].Value, userInfo, expiresSliding, true);
                            if (tokenResult != null)
                            {
                                result.ResData = tokenResult;
                                result.ErrCode = "0";
                                result.Success = true;
                            }
                        }
                    }
                }
                else
                {
                    //result.ErrMsg = ErrCode.err40004;
                    result.ErrCode = "40004";
                }
            }
            else
            {
                //result.ErrMsg = ErrCode.err40004;
                result.ErrCode = "40004";
            }
            return Content(JsonHelper.SerializeObject(result));
        }
    }
}
